<template>
  <div class="app-container">

    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
      <el-form-item slot="button">
        <el-button v-hasPermi="['miniProgram:app:add']" type="success" @click="handleAdd">添加</el-button>
      </el-form-item>
      <template slot="selectRemote" slot-scope="{param}">
        <template v-if="param === 'admin_id_search'">
          <YxhySelectRemote
            :value.sync="queryParams.admin_id_search"
            :request-fn="queryUserAllList"
            :request-key="`name_search`"
            :response-id="`id`"
            :response-name="`chinese_name`"
            :placeholder="`请选择操作人`"
          />
        </template>
      </template>
    </YxhyTableQuery>

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button v-hasPermi="['miniProgram:app:edit']" type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <template v-if="scope.row.flag === 0">
                <el-button v-hasPermi="['miniProgram:app:flag']" type="primary" size="mini" @click="handleSwitchFlag(scope.row)">启用</el-button>
              </template>
              <template v-else-if="scope.row.flag === 1">
                <el-button v-hasPermi="['miniProgram:app:flag']" type="info" size="mini" @click="handleSwitchFlag(scope.row)">关闭</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="渠道ID" prop="channel">
          <el-input v-model="form.channel" placeholder="请输入10000~60000的值" type="number" />
        </el-form-item>
        <el-form-item label="渠道名称" prop="channel_name">
          <el-input v-model="form.channel_name" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="应用" prop="product_id">
          <YxhyTableDialogSelect
            ref="yxhyTableDialogSelectApp"
            :btn-text="`选择应用`"
            :table-key="`id`"
            :table-name="`product_name`"
            :detail-data="isEdit ? formDetail : null"
            :detail-id-key="`applet`"
            :columns="columnsSelectApp"
            :query-params="queryParamsSelectApp"
            :query-columns="queryColumnsSelectApp"
            :request-fn="queryListApp"
            @selectResult="handleSelectResultApp"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { CLIENT, columnsSelectApp, columnsStatic, FLAG } from './Ds.js'
import { queryUserAllList } from '@/api/system/account'
import { queryListApp } from '@/api/miniProgram/app'
import { addChannelApp, editChannelApp, queryPageChannelAppList, updateChannelSwitch } from '@/api/channel/channelApp'
export default {
  name: 'ChannelAddList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        channel_id_search: undefined,
        channel_name_search: undefined,
        admin_id_search: undefined
      },
      // 查询表单
      queryColumns: [{
        label: '',
        placeholder: '请输入渠道Id',
        type: 'input',
        param: 'channel_id_search'
      }, {
        label: '',
        placeholder: '请输入渠道名称',
        type: 'input',
        param: 'channel_name_search'
      },
      {
        label: '',
        placeholder: '请选择操作人',
        type: 'selectRemote',
        param: 'admin_id_search'
      }],
      loading: false,
      // 表格列
      columns: columnsStatic,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      form: {
        product_id: undefined,
        channel: undefined,
        channel_name: undefined,
        flag: 1 // 1启动  0关闭
      },
      formDetail: null,
      // 表单校验
      rules: {
        channel: [
          { required: true, message: '请输入渠道ID', trigger: ['blur', 'change'] }
        ],
        channel_name: [
          { required: true, message: '请输入渠道名称', trigger: ['blur', 'change'] }
        ],
        product_id: [
          { required: true, message: '请选择应用', trigger: ['blur', 'change'] }
        ]
      },
      queryUserAllList,

      // 选择应用
      queryParamsSelectApp: {
        product_id_search: undefined,
        product_name_search: undefined
      },
      queryColumnsSelectApp: [
        {
          label: '',
          placeholder: '请输入应用ID',
          type: 'input',
          param: 'product_id_search'
        }, {
          label: '',
          placeholder: '请输入应用名称',
          type: 'input',
          param: 'product_name_search'
        }
      ],
      columnsSelectApp,
      queryListApp
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryPageChannelAppList({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.forEach(e => {
        const { client, flag } = e
        e.client_text = CLIENT[client]
        e.flag_text = FLAG[flag]
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 清空搜索按钮操作 */
    handleClear() {
      this.init()
    },
    reset() {
      this.form = {
        product_id: undefined,
        channel: undefined,
        channel_name: undefined,
        flag: 1 // 1启动  0关闭
      }
      this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs.yxhyTableDialogSelectApp.onReset()
      })
    },
    /** 接收短剧选择 */
    handleSelectResultApp(rows) {
      const library_id_str = rows.map(item => item.id).toString()
      this.form.product_id = library_id_str
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.title = '添加APP应用渠道'
      this.reset()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true
      this.title = '修改APP应用渠道'

      const { id, applet, name, flag } = row
      const transRow = {
        product_id: applet,
        channel_id: id,
        channel: id,
        channel_name: name,
        flag,
        applet,
        id
      }
      this.form = JSON.parse(JSON.stringify(transRow))
      this.$nextTick(() => {
        this.formDetail = JSON.parse(JSON.stringify(transRow))
      })
    },
    /** 修改状态按钮操作 */
    handleSwitchFlag(row) {
      const { id, flag } = row
      const boolean_flag = flag === 1
      updateChannelSwitch({
        channel_id: id,
        flag: boolean_flag ? 0 : 1
      }).then(() => {
        this.$modal.msgSuccess('操作成功')
        this.open = false
        this.init()
      })
    },
    cancel() {
      this.open = false
    },
    submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.form.update_channel_id = this.form.channel
            editChannelApp(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addChannelApp(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.link-panel .el-button + .el-button{
  margin-left: 0;
  margin-top: 10px;
}
.item-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  .item-panel {
    width: 32%;
    background-color: #f8f8f8;
    padding: 10px;
    margin-bottom: 20px;
  }
}
.item-box:after {
  content: '';
  width: 30%;
}

.detail-hover {
  color: #409eff
}

.detail-hover:hover {
  cursor: pointer;
}

.detail-text {
  margin-left: 20px;
}
</style>
